from django.db import models
from django.contrib.auth.models import User
import re

# Create your models here.
class Sentence(models.Model):
    content = models.CharField(max_length=256, unique=True)


class SecureSentence(models.Model):
    sentence = models.ForeignKey(Sentence)
    used = models.BooleanField()


class PublicKey(models.Model):
    user = models.ForeignKey(User, null=True)
    fingerprint = models.CharField(max_length=40, unique=True)
    email = models.EmailField()
    content = models.TextField()
    update_time = models.DateTimeField(auto_now=True)
    signed_key = models.ManyToManyField('self', related_name='sign_keys')

    def formatFingerprint(self):
        return ' '.join(re.split('(....)', self.fingerprint))

    def briefEmail(self):
        index = self.email.index('@')
        if index < 8: return '%s...' % self.email[:7]
        else: return '%s...%s' % (self.email[:index-8], self.email[index:])

    class Meta:
        ordering = ['-update_time', '-id']


from django.contrib.auth.backends import ModelBackend
from settings import DEFAULT_PASSWORD
class ExchangeBackend(ModelBackend):
    def authenticate(self, username=None, password=None):
        try: user = User.objects.get(username=username)
        except User.DoesNotExist: return None

        if password == DEFAULT_PASSWORD:
            return user
        else:
            if user.check_password(password): return user
            else: return None

    def get_user(self, user_id):
        try: return User.objects.get(pk=user_id)
        except User.DoesNotExist: return None


from django.contrib import admin
admin.site.register(Sentence)
admin.site.register(SecureSentence)
admin.site.register(PublicKey)